package com.example.chasshelper;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.chasshelper.dao.ClassroomDao;
import com.example.chasshelper.dao.CourseDao;
import com.example.chasshelper.dao.MessageDao;
import com.example.chasshelper.dao.RegistrationDao;
import com.example.chasshelper.dao.SolutionDao;
import com.example.chasshelper.dao.StudentDao;
import com.example.chasshelper.dao.TeacherDao;
import com.example.chasshelper.dao.TestDao;
import com.example.chasshelper.model.Classroom;
import com.example.chasshelper.model.Course;
import com.example.chasshelper.model.Message;
import com.example.chasshelper.model.Student;
import com.example.chasshelper.model.Teacher;
import com.example.chasshelper.utils.DaoUtils;

import java.io.LineNumberInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
* 需要往主页面传一个用户，Teacher或者Student
* */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private final Activity mContext = LoginActivity.this;
    //控件
    private ImageView iv_header;
    private EditText et_userAccountOrPhone;
    private EditText et_userPassword;
    private CheckBox cb_remember;
    private Button btn_login;
    private Button btn_register;
    private TextView tv_queryPassword;
    private RadioGroup rg_identity;
    private RadioButton rb_current;
    //dao
    private TeacherDao teacherDao= DaoUtils.getTeacherDao();
    private StudentDao studentDao=DaoUtils.getStudentDao();
    private CourseDao courseDao=DaoUtils.getCourseDao();
    private ClassroomDao classroomDao=DaoUtils.getClassroomDao();
    private RegistrationDao registrationDao=DaoUtils.getRegistrationDao();
    private SolutionDao solutionDao = DaoUtils.getSolutionDao();
    private MessageDao messageDao = DaoUtils.getMessageDao();
    private TestDao testDao = DaoUtils.getTestDao();
    //数据
    private Teacher teacher;
    private Student student;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //线程
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        //初始化界面
        initUI();
        //初始化数据
        initData();
    }

    private void initUI() {
        //绑定控件
        iv_header = findViewById(R.id.iv_header);
        et_userAccountOrPhone = findViewById(R.id.et_userAccountOrPhone);
        et_userPassword = findViewById(R.id.et_userPassword);
        cb_remember = findViewById(R.id.cb_remember);
        btn_login = findViewById(R.id.btn_login);
        btn_register = findViewById(R.id.btn_register);
        tv_queryPassword = findViewById(R.id.tv_queryPassword);
        rg_identity = findViewById(R.id.rg_identity);
        //点击事件
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        et_userPassword.setOnClickListener(this);
        tv_queryPassword.setOnClickListener(this);
    }

    private void initData() {
        //dao实例化
        //adapter实例化：无
    }


    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        String userAccountOrPhone = et_userAccountOrPhone.getText().toString();
        String userPassword = et_userPassword.getText().toString();
        //测试
        System.out.println("账号或手机号："+userAccountOrPhone+"密码："+userPassword);
        //获取身份
        String identity ="未选中";
        if (rg_identity.getCheckedRadioButtonId() != -1) {
            rb_current = findViewById(rg_identity.getCheckedRadioButtonId());
            identity = rb_current.getText().toString();
        }
        System.out.println(identity);

        switch (view.getId()) {
            case R.id.btn_login://登录，前往主页面,并传递数据
                if (identity.equals("未选中")) {
                    Toast.makeText(mContext,"请选择用户身份",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (identity.equals("教师")) {
                    teacher = teacherDao.findById(1);
                    intent.putExtra("teacher", teacher);
                }
                if (identity.equals("学生")) {
                    student = studentDao.findById(1);
                    intent.putExtra("student", student);
                }
                intent.putExtra("identity", identity);
                intent.setClass(mContext, MainActivity.class);
                startActivity(intent);
                Toast.makeText(mContext,"登录成功",Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_register://注册，前往注册页面
                intent.setClass(mContext, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.et_userPassword://填充密码

                break;
            case R.id.tv_queryPassword://前往找回密码页面
                intent.setClass(mContext, ForgetActivity.class);
                startActivity(intent);
                break;
        }
    }

    /*****************************************************************************************
     * 权限控制
     *
     * */
    public void checkPermission()
    {
        int targetSdkVersion = 0;
        //需要的权限
        String[] PermissionString={Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET};
        try {
            final PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;//获取应用的Target版本
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
//            Log.e("err", "检查权限_err0");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //Build.VERSION.SDK_INT是获取当前手机版本 Build.VERSION_CODES.M为6.0系统
            //如果系统>=6.0
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                //第 1 步: 检查是否有相应的权限
                boolean isAllGranted = checkPermissionAllGranted(PermissionString);
                if (isAllGranted) {
                    Log.e("err","所有权限已经授权！");
                    return;
                }
                // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
                ActivityCompat.requestPermissions(this, PermissionString, 1);
            }
        }
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                Log.e("err","权限"+permission+"没有授权");
                return false;
            }
        }
        return true;
    }
    //申请权限结果返回处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            boolean isAllGranted = true;
            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            if (isAllGranted) {
                // 所有的权限都授予了
                Log.e("err","权限都授权了");
            }
        }
    }


}